package top.ccm.ems.system.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.word.Word07Writer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Case;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.springframework.web.bind.annotation.*;

import top.ccm.ems.system.entity.*;
import top.ccm.ems.system.pojo.R;
import top.ccm.ems.system.service.*;
import top.ccm.ems.system.vo.ExamQuestionVo;
import top.ccm.ems.system.vo.QuestionVo;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ccm
 * @since 2021-11-26
 */
@RestController
@RequestMapping("/ems/exam")
@CrossOrigin
public class ExamController {

    @Resource
    private ExamService examService;

    @Resource
    private SingleChoiceQuestionService singleChoiceQuestionService;
    @Resource
    private MultipleChoicesQuestionService multipleChoicesQuestionService;
    @Resource
    private FillQuestionService fillQuestionService;
    @Resource
    private CaseQuestionService caseQuestionService;
    @Resource
    private TrueFalseQuestionService trueFalseQuestionService;

    private String[] type = {"单选题","多选题","判断题","填空题","案例题"};

    private String[] chinese = {"一","二","三","四","五"};

    private String[] abc = {"A","B","C","D","E","F","G"};

    @ApiOperation(value = "所有试卷列表")
    @GetMapping("/list")
    public R list(){
        return R.ok().data("data",examService.list(null));
    }

    @ApiOperation(value = "编辑题目")
    @PostMapping("/edit")
    public R edit(@RequestBody Exam exam){
        examService.updateById(exam);
        return R.ok();
    }

    @ApiOperation(value = "预览试卷")
    @PostMapping("/preview")
    public void preview(@RequestBody Exam exam, HttpServletResponse response) throws IOException{
        // response是HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        // test.docx是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=test.docx");
        ServletOutputStream out = null;
            out = response.getOutputStream();
        BufferedInputStream inputStream = FileUtil.getInputStream("D:/word/" + exam.getAuthor() + exam.getTitle() + exam.getName() + ".docx");
        int len=0;
        byte[] buffer=new byte[1024];
        while((len=inputStream.read(buffer))>0){
            out.write(buffer,0,len);
        }
        inputStream.close();
        out.close();

    }

    @ApiOperation(value = "添加试卷")
    @PostMapping("/add")
    public void add(@RequestBody Exam exam, HttpServletResponse response){
        List<SingleChoiceQuestion> singleChoiceQuestion;
        // response是HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        // test.docx是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=test.docx");
        Word07Writer word = word(exam);
        examService.save(exam);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
        }
        word.flush(FileUtil.file("D:/word/"+exam.getAuthor()+exam.getTitle()+exam.getName()+".docx"));
        // 写出到目标流
        word.flush(out);

        // 关闭writer，释放内存
        word.close();
        // 关闭输出Servlet流
        IoUtil.close(out);

    }

    public Word07Writer word(Exam exam) {

        Integer isExportAnswer = exam.getIsExportAnswer();

        Word07Writer word07Writer = new Word07Writer();
        // 1.1 保存试卷名称
        word07Writer.addText(ParagraphAlignment.CENTER,new Font("方正小标宋简体", Font.PLAIN, 20),  exam.getTitle());
        word07Writer.addText(ParagraphAlignment.CENTER,new Font("方正小标宋简体", Font.PLAIN, 25),  exam.getName());
        word07Writer.addText(ParagraphAlignment.CENTER,new Font("方正小标宋简体", Font.PLAIN, 12),  "（考试时间："+exam.getLastTime()+"分钟；总分："+exam.getScore()+"分）");

        // 2、得到当前试卷的题目列表
        for (int i = 0; i < exam.getQuestion().size(); i++) {
            ExamQuestionVo questionInfo = exam.getQuestion().get(i);
            if (questionInfo.getNumber() > 0){
                word07Writer.addText(new Font("宋体", Font.PLAIN, 13),
                chinese[i] + "、" + type[i] + "（每题" + questionInfo.getScore() + "分）");
                List<? extends Question> list;
                switch (i){
                    case 0:
                        list = singleChoiceQuestionService.list(new QueryWrapper<SingleChoiceQuestion>().last("ORDER BY RAND() LIMIT " + questionInfo.getNumber()));
                        selectQuestionParse(list,word07Writer,0);
                        break;
                    case 1:
                        list = multipleChoicesQuestionService.list(new QueryWrapper<MultipleChoicesQuestion>().last("ORDER BY RAND() LIMIT " + questionInfo.getNumber()));
                        selectQuestionParse(list,word07Writer,1);
                        break;
                    case 2:
                        list = trueFalseQuestionService.list(new QueryWrapper<TrueFalseQuestion>().last("ORDER BY RAND() LIMIT " + questionInfo.getNumber()));
                        for (int j = 0; j < list.size(); j++) {
                            TrueFalseQuestion question = (TrueFalseQuestion) list.get(j);
                            word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
                                    (j + 1) + ". " + question.getStem());
                        }
                        break;
                    case 3:
                        list = fillQuestionService.list(new QueryWrapper<FillQuestion>().last("ORDER BY RAND() LIMIT " + questionInfo.getNumber()));
                        for (int j = 0; j < list.size(); j++) {
                            FillQuestion question = (FillQuestion) list.get(j);
                            String stem = question.getStem().replaceAll("（","（       ");
                            stem = question.getStem().replaceAll("\\(","\\(       ");
                            word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
                                    (j + 1) + ". " +stem);
                        }
                        break;
                    case 4:
                        list = caseQuestionService.list(new QueryWrapper<CaseQuestion>().last("ORDER BY RAND() LIMIT " + questionInfo.getNumber()));
                        for (int j = 0; j < list.size(); j++) {
                            CaseQuestion question = (CaseQuestion) list.get(j);
                            String stem = question.getStem().replace("（","（    ");
                            word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
                                    (j + 1) + ". " +stem);
                            word07Writer.addText(new Font("宋体", Font.PLAIN, 10),"");
                            word07Writer.addText(new Font("宋体", Font.PLAIN, 10),"");
                            word07Writer.addText(new Font("宋体", Font.PLAIN, 10),"");
                        }
                        break;
                    default:

                }

            }

        }

        return word07Writer;
    }

    private void selectQuestionParse(List<? extends Question> list,Word07Writer word07Writer,int flag){
        for (int j = 0; j < list.size(); j++) {
            if (flag==0){
                SingleChoiceQuestion question = (SingleChoiceQuestion) list.get(j);
                word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
                        (j+1) + ". " + question.getStem());
                JSONArray options = JSON.parseArray(question.getOptions());
                for (int k = 0; k < options.size();k++){
                    word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
                            "    "+abc[k] + ". " + options.getString(k));
                }
            }else{
                MultipleChoicesQuestion question = (MultipleChoicesQuestion) list.get(j);
                word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
                        (j+1) + ". " + question.getStem());
                JSONArray options = JSON.parseArray(question.getOptions());
                for (int k = 0; k < options.size();k++){
                    word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
                            "    "+abc[k] + ". " + options.getString(k));
                }
            }


        }
    }


    @ApiOperation(value = "通过id删除")
    @DeleteMapping("delete")public R delete(@RequestParam(name = "id") String id){
        examService.removeById(id);
        return R.ok();
    }

    @ApiOperation(value = "批量删除")
    @DeleteMapping("/deleteBatch")
    public R deleteBatch(@RequestParam(name = "ids") String ids){
        examService.removeByIds(Arrays.asList(ids.split(",")));
        return  R.ok();
    }
}

